//
//  QSSelectCompanyViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/4/21.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSSelectCompanyViewController.h"
#import "QSHeaderSearchView.h"
#import "QSProblemReprotInterface.h"
#import "QSCompanyCell.h"
#import "BRPickerView.h"
@interface QSSelectCompanyViewController ()<QSHeaderSearchViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (nonatomic, strong)QSHeaderSearchView *headerSearchView;
/** 选择街道label*/
@property (nonatomic, strong)UILabel *selectStreetLabel;
/** 右侧图片*/
@property (nonatomic, strong)UIImageView *rightImageView;

@property (nonatomic, strong)NSArray *townArr;//街道数组

@property (nonatomic, strong)NSString *townShipId;//街道id
@property (nonatomic, strong)NSString *name;//公司名称
@end
static NSString * const companyCell = @"CompanyCell";

@implementation QSSelectCompanyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupForDismissKeyboard];//键盘回收
    [self getTownList];//请求街道列表
    [self configSubView];
    [self addRefreshHeader];
    [self addRefreshFooter];
    [self startRefreshing];
    
}

- (void)configSubView{
    self.tableView.frame = CGRectMake(0, kNavgationBarHeight + kRealValue(10 + 34), kScreenWidth, kScreenHeight - kNavgationBarHeight - 44);
    self.view.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"QSCompanyCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:companyCell];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    [self.view addSubview:self.headerSearchView];
    [self.view addSubview:self.selectStreetLabel];
    [self.selectStreetLabel addSubview:self.rightImageView];
    [self.selectStreetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRealValue(10));
        make.right.equalTo(self.view).offset(- kRealValue(10));
        make.top.equalTo(self.headerSearchView.mas_bottom).offset(kRealValue(10));
        make.height.offset(kRealValue(34));
    }];
    
    [self.rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_selectStreetLabel);
        make.right.equalTo(_selectStreetLabel).offset(- kRealValue(5));
        make.width.height.offset(kRealValue(22));
    }];
}

- (QSHeaderSearchView *)headerSearchView{
    if (!_headerSearchView) {
        _headerSearchView = [[QSHeaderSearchView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavgationBarHeight)];
        _headerSearchView.delegate = self;
    }
    return _headerSearchView;
    
}

#pragma mark - Lazy Load
- (UILabel *)selectStreetLabel{
    if (!_selectStreetLabel) {
        _selectStreetLabel = [UILabel labelWithName:@"  所属镇街" font:[UIFont QSFontOfSize13] textColor:[UIColor QSColorBlack666666] textAlignment:NSTextAlignmentLeft];
        _selectStreetLabel.layer.cornerRadius = 5;
        _selectStreetLabel.layer.masksToBounds = YES;
        _selectStreetLabel.userInteractionEnabled = YES;
        _selectStreetLabel.backgroundColor = [UIColor QSColorWhiteFFFFFF];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectStreetAction:)];
        [_selectStreetLabel addGestureRecognizer:tap];
    }
    return _selectStreetLabel;
}

- (UIImageView *)rightImageView{
    if (!_rightImageView) {
        _rightImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_select_open"]];
    }
    return _rightImageView;
}
- (void)getTownList{
    [QSProblemReprotInterface getApiTownListListWithBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.townArr = result[@"list"];
//            [self.tableView reloadData];
        }
    }];
}

#pragma mark - Action
- (void)selectStreetAction:(UIButton *)sender{
    [self.headerSearchView.searchTextField resignFirstResponder];

    if (_townArr.count) {
        NSMutableArray *copyCompanyArr = [NSMutableArray array];
        for (NSDictionary *dic in _townArr) {
            NSString *companyName = [dic objectForKey:@"name"];
            [copyCompanyArr addObject:companyName];
        }
        [BRStringPickerView showStringPickerWithTitle:@"请选择街道" dataSource:copyCompanyArr defaultSelValue:nil resultBlock:^(id selectValue) {
            for (NSDictionary *dic in self.townArr) {
                if ([dic[@"name"] isEqualToString:selectValue]) {
                    self.selectStreetLabel.text = [NSString stringWithFormat:@"  %@", selectValue];
                    self.townShipId = (NSString *)dic[@"id"];
                    NSLog(@"%@", self.townShipId);
                    //选中之后右侧按钮可以清空
                    [self.headerSearchView.rightButton setTitle:@"清空" forState:UIControlStateNormal];
                    [self tableViewShouldUpdateDataByPageIndex:1];//取出选中id搜索
                    break;
                }
            }
        }];
    }else{
        [QSAppKeyWindow showAutoHideHudWithText:@"没有街道可以选择!"];
    }
}

#pragma mark - HeaderSearchViewDelegate
//开始搜索企业
- (void)headerSearchViewDidSearchAction:(QSHeaderSearchView *)searchView{
    if (searchView.searchTextField.text.length > 0) {
        self.name = searchView.searchTextField.text;
        NSLog(@"name = %@", self.name);
        [self tableViewShouldUpdateDataByPageIndex:1];
    }
}

//清空操作
- (void)headerSearchViewDidClickClear:(QSHeaderSearchView *)searchView{
        searchView.searchTextField.text = @"";
        self.name = @"";
        self.townShipId = @"";
        self.selectStreetLabel.text = @"  所属镇街";
        [searchView.rightButton setTitle:@"取消" forState:UIControlStateNormal];
        [self tableViewShouldUpdateDataByPageIndex:1];
}

//返回上一页
- (void)headerSearchViewDidClickBack:(QSHeaderSearchView *)searchView{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault; //UIStatusBarStyleLightContent  白
}
#pragma mark - TableViewDelegate && DataSource
- (void)tableViewShouldUpdateDataByPageIndex:(NSInteger)pageIndex{
    [QSAppKeyWindow showIndeterminateHudWithText:@"加载中..."];
    [QSProblemReprotInterface getApiCompanyListWithPageIndex:pageIndex TownShipId:_townShipId CompanyName:_name andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSProblemCompanyListModel * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            if (pageIndex == 1) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:result.list];
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
            [self.tableView reloadData];
            [self.tableView qs_endRefreshing];
            if (pageIndex >= result.pages) {
//                self.tableView.mj_footer.hidden = YES;
                [self endRefreshingWithNoMoreData];
            }else{
                self.tableView.mj_footer.hidden = NO;
            }
        }
    }];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QSCompanyCell *cell = [tableView dequeueReusableCellWithIdentifier:companyCell];
    cell.model = self.dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kRealValue(80 + 10);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    QSProblemCompanyModel *model = self.dataArray[indexPath.row];
    if (self.didSelectCompanyFinish) {
        self.didSelectCompanyFinish(model.key, model.label);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
    [self.tableView endEditing:YES];
    [self.selectStreetLabel endEditing:YES];
    QSCompanyCell *cell = [self.tableView dequeueReusableCellWithIdentifier:companyCell];
    [cell.contentView endEditing:YES];
}

#pragma mark - DZNEmptyDataSetSource
/**
 *  返回标题文字
 */
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"暂时没有数据哦!";
    NSDictionary *attributes = @{ NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f],
                                     NSForegroundColorAttributeName: [UIColor QSColorBlack666666] };
    return [[NSAttributedString alloc]initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    scrollView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    return [UIImage imageNamed:@"ic_problem_null"];
}


@end
